import 'package:flutter/material.dart';
import '../static_var.dart';
import '../model/ex_stream.dart';
import '../utils.dart';
import '../user_proof.dart';
import './loading_widget.dart';
import './gradient_btn.dart';
import '../model/my_socket.dart';
import '../model/socket_msg.dart';
import '../widget/loading_gradient_btn.dart';
import '../model/cus_dialog.dart';
import '../widget/nobk_dialog.dart';

class FriendsList extends StatelessWidget {
  final ExStream<List<Map<String, dynamic>>> friendsStream = ExStream<List<Map<String, dynamic>>>(null);
  final bool hasInviteBtn;
  FriendsList({this.hasInviteBtn = false});
  final ExStream<List<String>> hadInviteStream = ExStream<List<String>>([]);
  bool onlyShowOnline = true;
  final ExStream<bool> onlyShowOnlineStream = ExStream<bool>(true);

  ExStream<bool> btnAddFriendStream;
  TextEditingController friendNameController = TextEditingController();
  String friendName = '';

  void loadFriendsData(BuildContext context) async {
    friendsStream.setData(null);
    hadInviteStream.setData([]);
    Utils.get(context: context, url: StaticVar.remoteUrl + '/getFriends', data: {'user_id': UserProof.userId, 'only_online': onlyShowOnlineStream.data}, success: (Map res){
      friendsStream.setData(List<Map<String, dynamic>>.from(res['data']));
    });
  }

  void addFriend(BuildContext context) async {
    bool btnStreamData = this.btnAddFriendStream.data;
    if(null == btnStreamData || !btnStreamData) {
      if('' != friendName) {
        btnAddFriendStream.setData(true);
        Utils.post(context: context, url: StaticVar.remoteUrl + '/addFriend', data: {'user_id': UserProof.userId, 'friend_name': friendName},
          success: (res){
            friendNameController.clear();
            Navigator.of(context).pop();
            CusDialog.showSuc(context, '发送成功');
          }, finnaly: (){
            btnAddFriendStream.setData(false);
          }
        );
      }else {
        CusDialog.showError(context, '好友昵称不能为空');
      }
    }
  }

  void showAddFriend(BuildContext context) {
    if(null != btnAddFriendStream) {
      btnAddFriendStream.dispose();
    }
    btnAddFriendStream = ExStream<bool>(false);
    nobkDialog(
      context: context,
      builder: (BuildContext context) {
        return SimpleDialog(
          title: Container(
            alignment: Alignment.center,
            child: Text('添加好友', style: TextStyle(color: StaticVar.yellowColor, fontSize: 25),),
          ),
          contentPadding: EdgeInsets.only(top: 0, bottom: 10, left: 10, right: 10),
          children: <Widget>[
            TextField(
              controller: friendNameController,
              style: TextStyle(color: StaticVar.blueColor,),
              cursorColor: StaticVar.blueColor,
              cursorRadius: Radius.circular(0),
              onChanged: (val){
                friendName = val;
              },
              decoration: InputDecoration(
                labelText: "昵称",
                prefixIcon: Icon(Icons.face)
              )
            ),
            Container(
              margin: EdgeInsets.only(top: 15),
              child: LoadingGradientBtn(
                exStream: this.btnAddFriendStream,
                color: StaticVar.blueColor,
                width: 0,
                iconColor: Colors.white,
                child: Text('添加', style: TextStyle(color: Colors.white)),
                pressed: (){
                  addFriend(context);
                },
              )
            ),
          ],
        );
      }
    );
  }

  List<Widget> getFriendWidgets(List<Map> friendsData, List<String> hadInvite) {
    List<Widget> friendsWidgets = [];
    if(null != friendsData) {
      if(friendsData.length == 0) {
        friendsWidgets.add(Text('暂无好友'+(onlyShowOnlineStream.data?'在线':''), style: TextStyle(fontSize: 18, color: StaticVar.blueColor),));
      }else {
        bool firendIsInRoom;
        bool isOnline;
        friendsData.forEach((friend){
          firendIsInRoom = null != friend['isInRoom'] && friend['isInRoom'];
          isOnline = null != friend['online'] && friend['online'];
          friendsWidgets.add(
            Container(
              padding: EdgeInsets.symmetric(vertical: 5),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Icon(IconData(friend['sex']==0?0xe602:0xe640, fontFamily: 'iconfont'), size: 18, color: isOnline ? Colors.black : StaticVar.deepGreyColor,),
                        Container(width: 8,),
                        Text(friend['uname'], style: TextStyle(fontSize: 18, color: isOnline ? Colors.black : StaticVar.deepGreyColor),),
                        Container(width: 3,),
                        Icon(IconData(friend['sex']==0?0xe6e3:0xe657, fontFamily: 'iconfont'), size: 10, color: isOnline?(friend['sex']==0?Color.fromARGB(255,255,61,138):StaticVar.blueColor):StaticVar.deepGreyColor),
                        Text(isOnline?(firendIsInRoom?'（游戏中）':'（大厅中）') : '（离线）', style: TextStyle(color: isOnline?(firendIsInRoom ? StaticVar.yellowColor : StaticVar.blueColor):StaticVar.deepGreyColor, fontSize: 12),),
                      ],
                    ),
                  ),
                  !hasInviteBtn || firendIsInRoom ? Container() : hadInvite.contains(friend['id'])?GradientBtn(child: Text('已邀请', style: TextStyle(color: Colors.white, fontSize: 15)), width: 53, height: 20,colorType:3,pressed: null):GradientBtn(child: Text('邀请', style: TextStyle(color: Colors.white, fontSize: 15)), width: 53, height: 20,pressed: (){
                    hadInvite.add(friend['id']);
                    hadInviteStream.setData(hadInvite);
                    MySocket.sendMsg(type: SendMsgType.invite, data: {'friend_id': friend['id']});
                  },)
                ],
              ),
            )
          );
        });
      }
    }
    return friendsWidgets;
  }

  @override
  Widget build(BuildContext context) {
    loadFriendsData(context);
    return StreamBuilder<List<Map<String, dynamic>>>(
      stream: friendsStream.stream,
      initialData: friendsStream.data,
      builder: (BuildContext context, AsyncSnapshot<List<Map<String, dynamic>>> friendsData){
        return StreamBuilder(
          stream: hadInviteStream.stream,
          initialData: hadInviteStream.data,
          builder: (BuildContext context, AsyncSnapshot hadInvite){
            return SimpleDialog(
              contentPadding: EdgeInsets.all(12),
              titlePadding: EdgeInsets.only(top: 12, bottom: 8, left: 12, right: 12),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  GestureDetector(
                    child: Icon(IconData(0xe64c, fontFamily: 'iconfont'), size: 18, color: StaticVar.blueColor,),
                    onTap: (){
                      showAddFriend(context);
                    },
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text('好友列表', style: TextStyle(color: StaticVar.yellowColor, fontSize: 25),),
                      StreamBuilder(
                        stream: onlyShowOnlineStream.stream,
                        initialData: onlyShowOnlineStream.data,
                        builder: (BuildContext context, AsyncSnapshot data){
                          return Stack(
                            children: <Widget>[
                              Radio(
                                value: true,
                                activeColor: StaticVar.greenColor,
                                groupValue: data.data,
                                onChanged: (val){},
                                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap
                              ),
                              Positioned(
                                top: 0,
                                right: 0,
                                left: 0,
                                bottom: 0,
                                child:  GestureDetector(
                                  child: Container(
                                    color: Colors.transparent,
                                  ),
                                  onTap: (){
                                    onlyShowOnlineStream.triggerData();
                                    this.loadFriendsData(context);
                                  },
                                ),
                              )
                            ],
                          );
                          
                        },
                      )
                      // Switch.adaptive(
                      //   value: this.onlyShowOnline,
                      //   materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      //   onChanged: (val){
                      //     this.onlyShowOnline = val;
                      //   },
                      // )
                      // Text('（在线）', style: TextStyle(color: StaticVar.yellowColor, fontSize: 15),)
                    ],
                  ),
                  GestureDetector(
                    child: Icon(IconData(0xe67c, fontFamily: 'iconfont'), size: 18, color: StaticVar.blueColor,),
                    onTap: (){loadFriendsData(context);},
                  )
                ],
              ),
              children: null == friendsData.data ? <Widget>[LoadingWidget(hasBk: false, iconSize: 18,)] : getFriendWidgets(friendsData.data, hadInvite.data)
            );
          }
        );
      }
    );
  }
}